package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRspVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.utils.HttpUtils;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class OauthLoginController {

    String host="https://gitee.com";
    String path="/oauth/token";
    String method="post";
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth/getcode")
    public String oauthGetcode(@RequestParam("code") String code, HttpSession session) throws Exception {
        //根据code 拿到token
//        https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
        HashMap<String, String> body = new HashMap<>();
        body.put("grant_type","authorization_code");
        body.put("code",code);
        body.put("client_id","eea22ffaf22b9efa95de7478a99c51dfc793d1b13d81f7658cb0957a12d5ca32");
        body.put("redirect_uri","http://auth.gulimall.com/oauth/getcode");
        body.put("client_secret","c617d52af47539da27b87d880650ec01cc76f4fbe31b6e0ae1af772523de09c7");
        HttpResponse httpResponse = HttpUtils.doPost(host, path, method, new HashMap<String, String>(), null, body);
        if (httpResponse.getStatusLine().getStatusCode()==200){
            String entity = EntityUtils.toString(httpResponse.getEntity());
            SocialUser socialUser = JSON.parseObject(entity, SocialUser.class);
            //调用远程member 根据token判断是否注册过
            R r = memberFeignService.OauthLogin(socialUser);
            if (r.getCode()==0){
                MemberRspVo data = r.getData("data", new TypeReference<MemberRspVo>() {});
                session.setAttribute("loginUser",data);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }


        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
